<template>
    <div style="padding: 10px">
        <!--      功能区域-->
        <div style="margin: 10px 0">
            <el-button type="primary" @click="add()">新增</el-button>
            <el-popconfirm v-if="role === 1" title="确认删除吗？" @confirm="deleteBatch">
                <template #reference>
                    <el-button type="danger">批量删除</el-button>
                </template>
            </el-popconfirm>
        </div>
        <!--      搜索区域-->
        <div style="margin: 10px 0">
            <el-input v-model="search" placeholder="请输入关键字" style="width: 20%" clearable/>
            <el-button type="primary" style="margin-left: 10px" @click="load">查询</el-button>
        </div>
        <!--      数据展示-->
        <div id="data-div">
            <el-table :data="tableData" stripe style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55"/>
                <el-table-column prop="id" label="ID" sortable/>
                <el-table-column prop="title" label="标题"/>
                <el-table-column prop="author" label="作者"/>
                <el-table-column prop="time" label="发布时间"/>
                <el-table-column fixed="right" label="操作">
                    <template #default="scope">
                        <el-button plain type="primary" @click="details(scope.row)">详情</el-button>
                        <el-button plain type="primary" @click="handleEdit(scope.row)">编辑</el-button>
                        <el-popconfirm title="确认删除吗？" @confirm="handleDelete(scope.row.id)">
                            <template #reference>
                                <el-button plain style="color: red">删除</el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
        </div>


        <div style="margin: 10px 0">
            <el-pagination
                    :currentPage="currentPage"
                    :page-size="pageSize"
                    :page-sizes="[5, 10, 20]"
                    :small="small"
                    :disabled="disabled"
                    :background="background"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
            />

            <el-dialog
                    v-model="dialogVisible"
                    title="输入信息"
                    width="50%"
            >
                <el-form :model="form" label-width="120px">
                    <el-form-item label="标题">
                        <el-input v-model="form.title" style="width: 80%"/>
                    </el-form-item>

                    <div id="div1"></div>
                </el-form>
                <template #footer>
                  <span class="dialog-footer">
                    <el-button @click="cancel">取消</el-button>
                    <el-button type="primary" @click="save()"
                    >确认</el-button
                    >
                  </span>
                </template>
            </el-dialog>

            <el-dialog
                    v-model="vis"
                    title="详情"
                    width="50%"
            >
                <el-card>
                    <div v-html="detail.content" style="min-height: 150px"></div>
                </el-card>
            </el-dialog>
        </div>
    </div>
</template>

<script>

    import api from "../api/index"
    import {ElMessage} from "element-plus";
    import E from 'wangeditor'
    import cookie from "@/utils/cookie";

    let editor = null

    export default {
        name: 'News',
        data() {
            return {
                search: '',
                currentPage: 1,
                pageSize: 10,
                total: 0,
                tableData: [],
                dialogVisible: false,
                form: {},
                fileList: [],
                cover: '',  // 临时储存原图片的url
                detail: {},
                vis: false,
                role: 2,
                user: {},
                ids: []
            }
        },
        created() {
            this.load()

            // 取出cookie里面的用户信息再次判断role（用户角色）不被恶意修改
            let userJson = cookie.getCookie("user")
            let userObj = JSON.parse(userJson)
            this.user.username = userObj.data.username
            this.user.password = userObj.data.password

            // 重新向后台获取user对象
            api.login(this.user).then(res => {
                this.role = res.data.data.role
            })
        },
        methods: {
            deleteBatch() {
                if (!this.ids.length) {
                    ElMessage.warning("请选择数据！")
                    return
                }
                api.deleteBatch(this.ids).then(res => {
                    this.handleResult_1(res, "批量删除成功", "删除失败")
                })
            },
            handleSelectionChange(val) {
                this.ids = val.map(v => v.id)   // [{id,name}, {id,name}] => [id,id]
            },
            details(row) {
                this.detail = row
                this.vis = true
            },
            load() {
                api.getNews({
                    params: {
                        pageNum: this.currentPage,
                        pageSize: this.pageSize,
                        search: this.search
                    }
                }).then(res => {
                    this.total = res.data.data.total
                    this.tableData = res.data.data.records
                })
            },
            add() {
                this.dialogVisible = true
                this.form = {}

                this.$nextTick(() => {
                    if (editor == null) {
                        editor = new E('#div1')
                        editor.create()
                    }
                    editor.txt.html('')
                })
            },
            save() {
                this.form.content = editor.txt.html()   // 将编辑器的值（html文本）存form的content里

                if (this.form.id) {  //更新
                    api.updateNews(this.form).then(res => {
                        this.handleResult_1(res, '更新成功', '更新失败')
                    }).catch(res => {
                        this.handleResult_2('更新失败')
                    })
                } else {    // 新增
                    // 取出cookie里面的用户信息，判断用户是否登录
                    let userJson = cookie.getCookie("user")
                    let user = JSON.parse(userJson)
                    if (!user) {
                        this.$router.replace("/login")   // 未登录则跳转到登录界面
                    } else {
                        this.form.author = user.data.nickName
                    }
                    api.addNews(this.form).then(res => {
                        this.handleResult_1(res, '新增成功', '新增失败')
                    }).catch(res => {
                        this.handleResult_2('新增失败')
                    })
                }
                this.cancel()
            },
            cancel() {
                this.dialogVisible = false
                this.form = {}  // 清空表单

                editor.destroy()
                editor = new E('#div1')
                editor.create()
            },
            handleEdit(row) {
                this.form = JSON.parse(JSON.stringify(row))
                this.dialogVisible = true
                this.cover = this.form.cover
                this.$nextTick(() => {
                    if (editor == null) {
                        editor = new E('#div1')
                        editor.create()
                    }
                    editor.txt.html(row.content)
                })
            },
            handleDelete(id) {
                api.deleteNews(id).then(res => {
                    this.handleResult_1(res, '删除成功', '删除失败')
                }).catch(res => {
                    this.handleResult_2('删除失败')
                })
            },
            handleSizeChange(pageSize) {    // 改变当前每页的显示个数触发
                this.pageSize = pageSize
                this.load()
            },
            handleCurrentChange(pageNum) {    // 改变当前页码触发
                this.currentPage = pageNum
                this.load()
            },
            handleResult_1(res, msg1, msg2) {   // 提示操作成功或者失败
                if (res.data.code == "0") {
                    ElMessage({
                        message: msg1,
                        type: 'success'
                    })
                    this.load()    // 操作成功后重载数据
                } else {
                    ElMessage.error(msg2)
                }
            },
            handleResult_2(msg) {   // 操作异常时提示
                ElMessage.error(msg)
            }
        },
        beforeDestroy() {
            const editor = this.editor
            if (editor == null) return
            editor.destroy() // 组件销毁时，及时销毁编辑器
        }
    }

</script>

<style>
    #data-div {
        width: auto;
        height: 550px;
        overflow: hidden scroll;
    }
</style>
